var Dict = function () {

    this.$grid_selector = $("#dict-grid-table");
    this.pager_selector = "#dict-grid-pager";

    // 请求url
    this.URL = {
        ADD: '/system/dict/add',
        EDIT: '/system/dict/{{id}}',
        DEL: '/system/dict/{{id}}',
        GET: '/system/dict/{{id}}',
        SUB_GET: '/system/dict/get/{{parentId}}'
    };

    var self = this;
    this.colModel = [
        {
            name: 'hasChild', width: 10, formatter: function (cellValue) {
                return cellValue ? '<span class="glyphicon glyphicon-ok orange"></span>' : '';
            }
        },
        { name: 'dictId', hidden: true, width: 15, key: true },
        { name: 'parentId', hidden: true, width: 20 },
        { name: 'name', width: 20 },
        {
            name: 'key', width: 35, formatter: function (cellValue) {
                return '<code>' + cellValue + '</code>';
            }
        },
        { name: 'value', width: 20 },
        { name: 'sequence', width: 10 },
        { name: 'comment', sortable: false, width: 20 },
        {
            name: 'createdAt', width: 10, formatter: "date",
            formatoptions: { srcformat: 'Y-m-d', newformat: 'Y-m-d' }
        },
        {
            width: 25, sortable: false, formatter: function (cellValue, row) {
                return self.operatingTemplate({ rowId: row.rowId });
            }
        }
    ];

    this.operatingTemplate = _.template(
        '<div class="btn-group">' +
        '<button id="add_sub_dict_{{rowId}}" class="btn btn-sm btn-primary add_sub_dict">增加子字典</button>' +
        '<button id="del_dict_{{rowId}}" class="btn btn-sm btn-danger del_dict"><i class="ace-icon fa fa-trash-o white"></i></button>' +
        '<button id="edit_dict_{{rowId}}" class="btn btn-sm btn-info edit_dict"><i class="ace-icon fa fa-pencil white"></i></button>' +
        '</div>'
    );

    this.subTableTemplate = "<table class='table table-bordered'>\
                                <thead>\
                                    <tr><th>名称</th><th style='width: 235px;'>键</th><th>值</th><th>排序</th><th>备注</th><th width='92'>创建日期</th><th>操作</th></tr>\
                                </thead>\
                                <tbody></tbody>\
                            </table>";

    this.subRowTemplate = _.template(
        '<tr style="background-color: white;">\
            <td>{{name}}</td>\
            <td><code>{{key}}</code></td>\
            <td>{{value}}</td>\
            <td>{{sequence}}</td>\
            <td>{{comment}}</td>\
            <td>{{createdAt}}</td>\
            <td>\
                <div class="btn-group">\
                <button id="del_sub_dict_{{dictId}}" class="btn btn-sm btn-danger del_sub_dict"><i class="ace-icon fa fa-trash-o white"></i></button>\
                <button id="edit_sub_dict_{{dictId}}" class="btn btn-sm btn-info edit_sub_dict"><i class="ace-icon fa fa-pencil white"></i></button>\
                </div>\
            </td>\
        </tr>'
    );

    this.options = {
        moduleKey: 'system/dict',
        pager: this.pager_selector,
        sortname: 'sequence',
        caption: "字典列表",
        colNames: ['存在子字典', '字典ID', '父ID', '名称', '键', '值', '排序', '备注', '创建日期', '操作'],
        colModel: this.colModel,
        subGrid: true,
        navbarDefaultIcon: {
            add: false,
            edit: false,
            view: false,
            del: false
        },
        subGridRowExpanded: function (subGridId, rowId) {
            var $table = $(self.subTableTemplate);
            $.get(_.template(self.URL.SUB_GET)({ parentId: rowId })).done(function (data) {
                for (var idx in data) {
                    $table.find('tbody').append(self.subRowTemplate(data[idx]))
                }
            });
            $("#" + subGridId).html($table);
        }
    };

    this.template = _.template('<form id="form_dict_add" style="padding: 16px;" class="form-horizontal" method="post">\
                                <input type="hidden" name="dictId" value="{{dictId}}">\
                                <div class="form-group">\
                                    <label for="parentId" class="col-xs-1 control-label">父</label>\
                                    <div class="col-xs-5"><input readonly class="form-control" type="text" name="parentId" id="parentId" value="{{parentId}}"></div>\
                                    <label for="name" class="col-xs-1 control-label">名称</label>\
                                    <div class="col-xs-5"><input class="form-control" type="text" name="name" id="name" value="{{name}}"></div>\
                                </div>\
                                <div class="form-group">\
                                    <label for="value" class="col-xs-1 control-label">值</label>\
                                    <div class="col-xs-5"><input class="form-control" type="text" name="value" id="value" value="{{value}}"></div>\
                                    <label for="sequence" class="col-xs-1 control-label">排序</label>\
                                    <div class="col-xs-5"><input autocomplete="off" min="1" type="number" class="form-control" name="sequence" id="sequence" value="{{sequence}}"></div>\
                                </div>\
                                <div class="form-group">\
                                    <label for="comment" class="col-xs-1 control-label">备注</label>\
                                    <div class="col-xs-11"><input class="form-control" autocomplete="off" type="text" name="comment" id="comment" value="{{comment}}"></div>\
                                </div>\
                             </form>');

};

Dict.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector
            .xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "删除",
                    buttonicon: "fa fa-trash-o red",
                    onClickButton: function () {
                        $(this).getGridSelectedRow(function (rowData) {
                            self.delUI(rowData.dictId)
                        });
                    },
                    position: "first"
                })
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "编辑",
                    buttonicon: "fa fa-pencil blue",
                    onClickButton: function () {
                        $(this).getGridSelectedRow(function (rowData) {
                            self.editUI(rowData);
                        });
                    },
                    position: "first"
                })
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
                {
                    caption: '',
                    title: "添加",
                    buttonicon: "fa fa-plus-circle purple",
                    onClickButton: function () {
                        self.addUI($.Const.ROOT_ID)
                    },
                    position: "first"
                });

        // 绑定删除字典事件
        this.$grid_selector.delegate('.del_dict', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[2];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.delUI(row.dictId);
        });
        // 绑定编辑字典事件
        this.$grid_selector.delegate('.edit_dict', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[2];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.editUI(row);
        });
        // 绑定添加子字典事件
        this.$grid_selector.delegate('.add_sub_dict', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[3];
            var row = self.$grid_selector.jqGrid('getRowData', rowId);
            self.addUI(row.dictId);
        });
        // 绑定删除子字典事件
        this.$grid_selector.delegate('.del_sub_dict', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[3];
            self.delUI(rowId);
        });
        // 绑定编辑子字典事件
        this.$grid_selector.delegate('.edit_sub_dict', 'click', function (event) {
            var rowId = $(event.currentTarget).attr('id').split('_')[3];
            $.xumf.ajaxAndLoading({
                method: 'get',
                url: _.template(self.URL.GET)({id: rowId}),
            }).done(function (res) {
                res.success && self.editUI(res.data);
            });
        });
    },
    delUI: function (dictId) {
        var $grid_selector = this.$grid_selector;
        var self = this;
        $.xumf.confirm('删除所选记录？', function (index, layero) {
            $.xumf.ajaxAndLoading({
                type: 'delete',
                url: _.template(self.URL.DEL)({ id: dictId })
            }).done(function (res) {
                layer.close(index);
                res.success && $grid_selector.trigger("reloadGrid")
            });
        });
    },
    editUI: function (rowData) {
        var self = this;
        // 显示弹框
        layer.open({
            title: '编辑字典',
            area: ['50%', '280'],
            content: this.template(rowData),
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                self.editAction() && layer.close(index);
            }
        });
    },
    addUI: function (parentId) {

        var self = this;
        // 显示弹框
        layer.open({
            title: '添加字典',
            area: ['50%', '280'],
            content: this.template({
                dictId: 0,
                parentId: parentId,
                name: '',
                value: '',
                comment: '',
                sequence: ''
            }),
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                self.addAction() && layer.close(index);
            },
            success: function (layero, index) {
            }
        });
    },
    /**
     * 添加操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    addAction: function () {
        var $form = $('#form_dict_add');
        $form.attr('action', this.URL.ADD);
        return this.validateAction($form, 'POST');
    },
    /**
     * 编辑操作
     * @returns {boolean} 是否阻止dialog消失，true为消失，false则相反
     */
    editAction: function () {
        var $form = $('#form_dict_add');
        var dictId = $form.find('input[name=dictId]').val();
        $form.attr('action', _.template(this.URL.EDIT)({ id: dictId }));
        return this.validateAction($form, 'PUT');
    },
    /**
     * 验证与提交
     * @param $form 表单的jquery对象
     * @param type 表单类型
     * @returns {*} 验证是否成功
     */
    validateAction: function ($form, type) {
        var $grid_selector = this.$grid_selector;
        $form.validate({
            rules: {
                name: { required: true },
                parentId: { required: true },
                value: { required: true },
                sequence: { required: true },
                comment: { required: true }
            },
            errorElement: "em"
        });
        // 验证成功
        var valid = $form.valid();
        if (valid) {
            $.xumf.showLoading();
            $form.ajaxSubmit({
                type: type,
                success: function (res) {
                    $.xumf.hideLoading();
                    $.xumf.gritter(res);
                    res.success && $grid_selector.trigger("reloadGrid")
                }
            });
        }
        return valid;
    }
};

